package com._520it._01_many2one.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;


import com._520it._01_many2one.domain.Department;
import com._520it._01_many2one.domain.Employee;
import com._520it._01_many2one.mapper.DepartmentMapper;
import com._520it._01_many2one.mapper.EmployeeMapper;
import com._520it.util.MybatisUtil;
import org.junit.Test;


public class App {
	
	//先设置关系, 在保存各个方面
	@Test
	public void testSave() throws Exception {
		
		//mapper接口代理对象实现了接口中的方法, 因此才会有mapper接口对象调用empmapper.save(employee1);
		SqlSession session = MybatisUtil.getSession();
		EmployeeMapper empmapper = session.getMapper(EmployeeMapper.class);
		DepartmentMapper depmapper = session.getMapper(DepartmentMapper.class);
		
	   //创建对象,设置属性
		Employee employee1 = new Employee();
		employee1.setName("刘强东");
		
		Employee employee2 = new Employee();
		employee2.setName("王健林");
		
		Department department = new Department();
		department.setName("市场开发部");
		
	    //根据类的结构关系,维护对象间的关系, 将one设置为many方的属性
		employee1.setDept(department);
		employee2.setDept(department);
		
		//保存: many2one关系型的: 先保存one方, 在保存many方 
		//原因:先将部门保存起来, 才能查到部门信息
		depmapper.save(department);
		
		empmapper.save(employee1);
		empmapper.save(employee2);
		
		session.commit();
		session.close();
	}
	
	
	//发送额外SQL形式的查询
	@Test
	public void testGet() throws Exception {
		SqlSession session = MybatisUtil.getSession();
		EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
		Employee employee = mapper.get(2L);
		System.out.println("额外SQL的方式----" + employee.getId()+employee.getName());
		session.commit();
		session.close();
	}

	//显示内连接的方式查询
	@Test
	public void testList() throws Exception {
		SqlSession session = MybatisUtil.getSession();
		EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
		List<Employee> list = mapper.list();
		for (Employee employee : list) {
			System.out.println("显示外连接发送----"+ employee);
		}
		session.commit();
		session.close();
	}


	//一个表中的主键被另外只一张表所关联成为外键,
	// 要删除这张表中的数据,先要解除关联的关系,再删除

	@Test
	public void testDelete() throws Exception {
		SqlSession session = MybatisUtil.getSession();
		EmployeeMapper empmapper = session.getMapper(EmployeeMapper.class);
		DepartmentMapper depmapper = session.getMapper(DepartmentMapper.class);

		//将many方中的外键信息设置为null,就相当于删除了外键信息
		empmapper.deleteRealtion(3L);

		//删除外键信息后,再删除外键关联的表中的数据
        depmapper.delete(3L);

		session.commit();
		session.close();
	}
	
	
	
}
